//
//  RequestManager.m
//  pianke
//
//  Created by lanou3g on 15/6/4.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager

//初始化方法
- (instancetype)initWithRequestURL:(NSString *)urlString requestModel:(RequestModel)requestModel parameter:(NSString *)parameter{
    
    self = [super init];
    if (self) {
        _requestURL = urlString;
        _requestModel = requestModel;
        _requestParameter = parameter;
        _parameterDic = [[NSMutableDictionary alloc] init];
    }
    return self;
}

//手动开始请求的方法
- (void)startRequest{
    
    NSURL *url = [NSURL URLWithString: _requestURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    if (_requestModel == POST) {
        [self parameterDicToString];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[_requestParameter dataUsingEncoding:NSUTF8StringEncoding]];
        
    }
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}
//把参数的字典形式转化为字符串形式
- (void)parameterDicToString{
    
    if (_parameterDic.count != 0) {
        NSMutableArray *parameterArr = [NSMutableArray array];
        for (NSString *key in _parameterDic) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",key,_parameterDic[key]];
            [parameterArr addObject:str];
        }
        _requestParameter = [parameterArr componentsJoinedByString:@"&"];
        
    }
    
}
//开始响应请求的方法，在这里对自己的data进行初始化
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    self.data = [NSMutableData data];
    
}
//接受返回的data，此方法可以执行多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    [self.data appendData:data];
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    if (_delegate && [_delegate respondsToSelector:@selector(requestError:)]) {
        
        [_delegate requestError:error];
        
    }
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (_delegate && [_delegate respondsToSelector:@selector(requestDidFinishWithData:)]) {
        
        [_delegate requestDidFinishWithData:self.data];
        
    }
    
}

- (void)dealloc
{
    
    [_data release];
    [_parameterDic release];
    [_requestURL release];
    [_requestParameter release];
    [super dealloc];
    
}

@end
